import { Component, Input, OnInit, Output, SimpleChanges,TemplateRef,EventEmitter } from '@angular/core';
import { Router } from "@angular/router";
import { NziModalService } from "ng-zorro-iop/modal/nzi-modal.service";
import { NzMessageService } from "ng-zorro-antd";

import { FcsService } from "../../service/fcs.service";
import { CommonService } from "../../service/common.service";
import { FcsConfigComponent } from "../fcs-config/fcs-config.component";
import { Region, Function } from "../class/instance";
import { CookiesService,NziTmsService,NzModalRef } from 'ng-zorro-iop';
import { Environment } from '../../../environments/environment';
import { AbstractControl, AsyncValidatorFn, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { debounceTime, distinctUntilChanged, first, map, switchMap } from 'rxjs/operators';
import { Observable, Subscriber } from 'rxjs';
import {randomBytes} from 'crypto';

@Component({
  selector: 'app-fcs-table',
  templateUrl: './fcs-table.component.html',
  styleUrls: ['./fcs-table.component.less']
})
export class FcsTableComponent implements OnInit {
  @Input() groupId = '';
  @Input() name = '';
  @Input() groups;
  @Input() groupDisplayName;
  @Input() regionName;
  @Input() showGroupName: boolean = true;
  @Input() currentRegion: Region;
  @Output() voted = new EventEmitter<boolean>();
  @Input() inActions=[];
  isLoading = true;
  totalCount = 0;
  functionList = [];
  hasInputValue = false;
  pageSize = 10;
  pageNo = 1;
  errorMsg = '';

  statusMonitoringInterval = null;

  nziResourceTags;
  nziTmsLoading = false;
  changeCopyForm: FormGroup; // 表单
  private createResourceModal: NzModalRef;
  
  copyName:string;
  checked=false;
  originApplicationList;
	applicationList;
  applicationId: string; 
  selectApplicationId: string; // 应用下拉选择框选中的应用id
  notFind: boolean = false; //没有查找到对应的应用

  constructor(private router: Router,
    private fcsService: FcsService,
    private modalService: NziModalService,
    private msgService: NzMessageService,
    private commonService: CommonService,
    private fb: FormBuilder,
    private tmsService: NziTmsService
    
    ) {
      this.changeCopyForm = this.fb.group({
        copyApp:"",
        copyName:[null, [Validators.required,this.nameValidator()],[this.nameDuplicateValidator()]],
        copyCode:true,
        copyEdit:false,
        description:["",[Validators.maxLength(500)]]
      });
     }

  ngOnChanges(simpleChanges: SimpleChanges){
    this.getNewSearch(simpleChanges);
  }

  //获取标签
  getResourceTags(){
    const serviceAPI = `${Environment.application.serviceAPI}`; // 从application.json读取serviceAPI
   
    this.nziTmsLoading = true;
    this.tmsService.getTagList('fcs').then((data) => {
      this.nziResourceTags = data;
      // console.log(this.nziResourceTags)
      this.nziTmsLoading = false;
    }, (error) => {
      this.nziTmsLoading = false;
    });
  }


 


  getNewSearch(simpleChanges:SimpleChanges){
    let needNewSearch = false; //是否需要重新查询，当在定时触发器查询过程中，改变了条件，那么查询要重新赋值查询条件进行定时查询
    if(simpleChanges){
      if(simpleChanges.groupId && simpleChanges.groupId.currentValue != simpleChanges.groupId.previousValue){
        needNewSearch = true;
      }
      if(simpleChanges.name && simpleChanges.name.currentValue != simpleChanges.name.previousValue){
        needNewSearch = true;
      }
      if(simpleChanges.currentRegion && simpleChanges.currentRegion.previousValue && simpleChanges.currentRegion.currentValue['regionCode'] != simpleChanges.currentRegion.previousValue['regionCode']){
        needNewSearch = true;
      }
    }
    if(needNewSearch){
      if(this.statusMonitoringInterval){
        this.doClearInterval();
        this.statusMonitoringInterval = setInterval(()=>{
          this.getFunctionList(this.groupId,this.name);
        },5000)
      }
    }
  }

  ngOnInit() {
    // 添加时间戳和随机数字段
    this.changeCopyForm.addControl('timestamp', new FormControl(Date.now()));
    this.changeCopyForm.addControl('nonce', new FormControl(randomBytes(5).toString(36).substring(0, 9)));

    this.getResourceTags();
    this.getApplicationList();
  }

  successFun() {
    this.msgService.success('复制成功!');
  }

  ngOnDestroy() {
    this.doClearInterval();
  }

  doClearInterval() {
    clearInterval(this.statusMonitoringInterval);
    this.statusMonitoringInterval = null;
  }

  trackById(index: number, data: Function): string {
    return data.functionId;
  }

  createFunction() {
    let params = { groupDisplayName: this.groupDisplayName, regionCode: this.currentRegion['regionCode'], regionName: this.currentRegion['regionName'] };
    if (this.groupId.trim() && this.groupId != '0' && this.groupId != 'all') {
      params['groupId'] = this.groupId;
    }
    this.router.navigate(['/fcs-manage/function/create'], { queryParams: params });
  }

  editFunction(data) {
    this.modalService.create({
      nzTitle: '配置函数',
      nzMaskClosable: false,
      nzWidth: '7rem',
      nzContent: FcsConfigComponent,
      nzComponentParams: { fcsInstance: data, regionCode:this.currentRegion.regionCode },
      nzOnOk: async createInstance => {
        let isSuccess = await createInstance.submitForm();
        isSuccess && this.getFunctionList(this.groupId, this.name);
        return isSuccess;
      },
    });
  }

  /**
	 * 名称校验
	 * @param {FormControl} control 控件实例
	 */
	nameValidator() {
		return (control: FormControl): { [s: string]: boolean } => {
			let name: string = control.value;
			let pattern = new RegExp('^[a-z][-a-z0-9]{0,18}[a-z0-9]$');
			if (!pattern.test(name)) {
				return { functionName: true };
			}
			return null;
		}
	}

  nameDuplicateValidator() {
		return (control: FormControl): any => {
			return control.valueChanges.pipe(
				distinctUntilChanged(),
				debounceTime(400),
				switchMap(() => this.isUserNameExist(control.value)),
				map(res => res['exist'] === true ? { duplicated: true } : null),
				first()
			);
		};
	}
  isUserNameExist(name: string): Observable<any> {
		if (!this.notFind) {
			if (this && this.selectApplicationId) {
				return this.fcsService.determineFunctionDuplicate(this.selectApplicationId, name);
			}
		}
		return new Observable((observer: Subscriber<any>) => {
			setTimeout(() => {
				observer.next({ exist: false });
			}, 2000);
		});
	}

  getApplicationList() {
		this.fcsService.getGroupList().subscribe(res => {
			
			this.originApplicationList = JSON.parse(JSON.stringify(res));
			let a;
			this.applicationList = (res.length === 0 ? a : res);
		
		}, error => {
			this.errorMsg = error;
		
		})
	}

  copyFunction(copyFormContent: TemplateRef<{}>,data){

    // this.copyName = data.functionName + "-copy";
    this.changeCopyForm.get('copyName').setValue(data.functionName + "-copy")
    this.selectApplicationId = data.groupId
    
    
    this.createResourceModal = this.modalService.create({
      nzTitle: '函数复制',
      nzContent: copyFormContent,
      nzMaskClosable: false,
      nzClosable: true,
      nzWidth: 540,
      nzOnCancel: () => {
       this.changeCopyForm.reset();
      },
      nzOnOk:()=>{
        return new Promise((resolve, reject) => {
          let param: { [index: string]: any } = {};

          param['description'] = this.changeCopyForm.get('description').value;
          param['targetGroupId'] = this.changeCopyForm.get('copyApp').value;
          param['newFunctionName'] = this.changeCopyForm.get('copyName').value;
          param['isCopyConfig'] = this.changeCopyForm.get('copyEdit').value;
          
          
              this.fcsService.determineFunctionDuplicate(this.selectApplicationId,this.changeCopyForm.get('copyName').value).subscribe(res=>{
      
                if(res['exist'] === true){
                  
                  resolve(false);
                  this.msgService.error('名称重复');
                }else{
                  this.fcsService.copyFunction(data.groupId,data.functionId,param).subscribe(res=>{
                    // console.log(res.code)
                    if(res&&res.code){
                      resolve(false);
                     
                      this.msgService.error('复制失败！');
                    }else{
                      this.groupId = this.changeCopyForm.get('copyApp').value;
                      this.vote();
                      resolve(true);
                      this.getFunctionList(this.groupId,this.name);
                    }
                  },
                  err => {
                    this.modalService.closeAll();
                    
                    this.msgService.error('复制失败！');
                    resolve(false);
                  }
                  )
                }
              },
             )
              
            
        })
      }
      })
  }
  public vote() {
    this.voted.emit(this.changeCopyForm.get('copyApp').value);
  }

  groupChange(event){
this.selectApplicationId = event;
  }

  deleteFunction(data) {
    this.modalService.delete({
      nzTitle: '删除函数',
      nzContentTitle: `确定删除函数 <em>“${data.functionName}”</em> 吗？`,
      nzOnOk: () => {
        //返回一个promise对象才可以调用then等函数
        return new Promise((resolve, reject) => {
          this.fcsService.deleteFunction(data.groupId, data.functionId).subscribe(
            data => {
              if (data && data.code) {
                resolve(false);
                this.msgService.error(data['message'] || '删除失败！');
              } else {
                resolve(true);
                this.msgService.success('删除成功！');
                if (this.functionList.length <= 1) {
                  this.pageNo -= 1;
                  this.pageNo = this.pageNo <= 0 ? 1 : this.pageNo;
                }
                this.getFunctionList(this.groupId, this.name);
              }
            },
            err => {
              resolve(false);
            }
          );
        });
      },
      nzCancelText: '取消',
      nzOnCancel: () => { },
    });
  }

  getFunctionList(groupId, name = '') {
    this.isLoading = true;
    this.hasInputValue = this.name != '';
    if (groupId === 'all') {
      this.fcsService.getAllFunctions(this.pageNo, this.pageSize, name).subscribe(res => {
        this.totalCount = res.totalCount || 0;
        if (res.result) {
          if (res.result.length > 0) {
            this.functionList = res.result;
          } else {
            if (res.recordsFiltered <= 0 && res.recordsFiltered === res.totalCount) {
              this.functionList = res.result;
            }
          }
        }

        // for (let i = 0; i < this.functionList.length; i++) {
        //   let groupName = this.functionList[i].groupName;
        //   for (let j = 0; j < this.groups.length; j++) {
        //     if (groupName === this.groups[j].name) {
        //       this.functionList[i]['groupDisplayName'] = this.groups[j].displayName;
        //     }
        //   }
        // }
        this.commonService.translateRuntime(this.functionList);
        if (this.totalCount > 0 && this.functionList == []) {
          this.pageNo = Math.floor(this.totalCount / this.pageSize);
          this.pageNo = (this.pageNo === 0 ? 1 : this.pageNo);
          this.getFunctionList(groupId, name);
        }
        this.isLoading = false;

        // 如果有创建中或更新中的函数，并且还没有循环监控，则开启循环监控
        let needMonitoring = this.commonService.hasMiddleStatus(this.functionList);
        if (needMonitoring) {
          if (!this.statusMonitoringInterval) {
            this.statusMonitoringInterval = setInterval(() => {
              this.getFunctionList(groupId, name);
            }, 5000);
          }
        } else {
          this.doClearInterval();
        }
      }, error => {
        this.errorMsg = error;
        this.isLoading = false;
      })
    } else { //从应用详情中调过来的，或者是函数列表中选择了某个应用过来的
      this.fcsService.getFuctionList(groupId, this.pageNo, this.pageSize, name).subscribe(res => {
        this.totalCount = res.totalCount || 0;
        if (res.result) {
          if (res.result.length > 0) {
            this.functionList = res.result;
          } else {
            if (res.recordsFiltered <= 0 && res.recordsFiltered === res.totalCount) {
              this.functionList = res.result;
            }
          }
        }
        this.functionList = res.result || [];
        if (this.groupDisplayName) {
          this.functionList.forEach(item => {
            item['groupDisplayName'] = this.groupDisplayName;
          })
        } else if (this.groups) {
          for (let i = 0; i < this.functionList.length; i++) {
            let groupName = this.functionList[i].groupName;
            for (let j = 0; j < this.groups.length; j++) {
              if (groupName === this.groups[j].name) {
                this.functionList[i]['groupDisplayName'] = this.groups[j].displayName;
              }
            }
          }
        }
        this.commonService.translateRuntime(this.functionList);
        if (this.totalCount > 0 && this.functionList == []) {
          this.pageNo = Math.floor(this.totalCount / this.pageSize);
          this.pageNo = (this.pageNo === 0 ? 1 : this.pageNo);
          this.getFunctionList(groupId, name);
        }
        this.isLoading = false;

        // 如果有创建中或更新中的函数，并且还没有循环监控，则开启循环监控
        let needMonitoring = this.commonService.hasMiddleStatus(this.functionList);
        if (needMonitoring) {
          if (!this.statusMonitoringInterval) {
            this.statusMonitoringInterval = setInterval(() => {
              this.getFunctionList(groupId, name);
            }, 5000);
          }
        } else {
          this.doClearInterval();
        }
      }, error => {
        this.errorMsg = error;
        this.isLoading = false;
      })
    }
  }

}
